package com.yingsheng.bi.hks.service.comm;

import com.google.gson.Gson;
import com.yingsheng.bi.hks.basic.enums.XjyOssEnum;
import com.yingsheng.bi.hks.basic.exception.ServiceRuntimeException;
import com.yingsheng.bi.hks.basic.utils.HttpUtil;
import com.yingsheng.bi.hks.basic.utils.IOUtils;
import com.yingsheng.bi.hks.basic.utils.Utils;
import com.yingsheng.bi.hks.dto.IdCardOcrReq;
import com.yingsheng.bi.hks.dto.IdCardOcrRes;
import com.yingsheng.bi.hks.dto.ImageUploadReq;
import com.yingsheng.bi.hks.dto.ImageUploadRes;
import io.minio.ObjectWriteResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ImageUplodadService {

    @Value("${tencent.url}")
    private String urlPrefix;

    @Value("${temporaryFile}")
    private String temporaryFile;

    @Value("${chinadatapay.ocrImageUrl}")
    private  String ocrImageUrl;

    @Value("${chinadatapay.ocrUrl}")
    private  String ocrUrl;

    @Value("${chinadatapay.ocrKey}")
    private  String ocrKey;

    public ImageUploadRes imageUplodad(ImageUploadReq imageUploadReq) {
        String imageName = Utils.genUUid() + ".png";
        ObjectWriteResponse response = XjyOssEnum.USER_IMAGE.putObject(Base64.getDecoder().decode(imageUploadReq.getImageBase64()), imageName);
        String objectName = response.object();
        String bucketName = response.bucket();
        String url = urlPrefix + bucketName + objectName;
        ImageUploadRes res = new ImageUploadRes();
        res.setImageUrl(url);
        return res;
    }

    public IdCardOcrRes idCardOcr(IdCardOcrReq req) {
        IdCardOcrRes res = new IdCardOcrRes();
        String imgPath = temporaryFile + "/" + Utils.genUUid()+".png";
        IOUtils.write(imgPath, Base64.getDecoder().decode(req.getIdCardImgFront()));
        String POST_URL = ocrImageUrl+ocrKey;
        String imageId = HttpUtil.getImageId(imgPath,POST_URL);
        if (imageId==null){
            throw new ServiceRuntimeException("系统错误，idCardOcr！");
        }
        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("imageId", imageId);
        params.put("key",ocrKey);
        String result = null;
        try {
            result = HttpUtil.post(params,ocrUrl);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        log.info("result:" + result);
        Gson gson = new Gson();
        Map<String,Object> resultMap = gson.fromJson(result,Map.class);
        String code = resultMap.get("code").toString();
        if ("10000".equals(code)){
            Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
            res.setName(dataMap.get("name").toString());
            res.setIdCardNo(dataMap.get("idcard").toString());
        }
        return res;
    }
}
